package com.thoughtworks.oo.quantity;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class LengthUnit extends Unit {

    private static OrderedUnits orderedUnits = new OrderedUnits();

    public static final LengthUnit INCH = new LengthUnit("INCH", 1, null);
    public static final LengthUnit FEET = new LengthUnit("FEET", 12, INCH);
    public static final LengthUnit YARD = new LengthUnit("YARD", 3, FEET);
    public static final LengthUnit MILE = new LengthUnit("MILE", 1760, YARD);

    private String name;

    private LengthUnit(String name, int conversionFactor, LengthUnit unit) {
        super(conversionFactor, unit);
        this.name = name;
        orderedUnits.add(this);
    }

    @Override
    public String toString() {
        return name;
    }

    public static void visitAllUnits(UnitVisitor visitor) {
        orderedUnits.visitAllUnits(visitor);
    }

    private static class OrderedUnits {
        List<LengthUnit> orderedUnits;

        private OrderedUnits() {
            orderedUnits = new ArrayList<LengthUnit>();
        }

        public void add(LengthUnit lengthUnit) {
            orderedUnits.add(lengthUnit);
            Collections.sort(orderedUnits, new Comparator<LengthUnit>() {
                @Override
                public int compare(LengthUnit one, LengthUnit another) {
                    return another.getBaseAmount(1) - one.getBaseAmount(1);
                }
            });
        }

        public void visitAllUnits(UnitVisitor visitor) {
            for (LengthUnit unit : orderedUnits) {
                if (!visitor.visit(unit)) break;
            }
        }
    }
}
